package com.example.hybridmobiledemo.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Paint;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.hybridmobiledemo.R;
import com.example.hybridmobiledemo.databinding.ItemRvClaBinding;
import com.example.hybridmobiledemo.module.main.model.shop.bean.Commodity;
import com.example.hybridmobiledemo.module.main.model.shop.bean.CommodityTypeIdInfo;
import com.example.hybridmobiledemo.module.main.model.shop.bean.ShopCartInfo;
import com.example.hybridmobiledemo.util.ClaMySQLiteOpenHelper;
import com.example.hybridmobiledemo.util.MyClaDataAdapter;
import com.example.hybridmobiledemo.util.OkHttpUtils;
import com.google.gson.Gson;

import java.util.List;

import okhttp3.Call;

/**
 * @ClassName: ClaRViewAdapter$
 * @Description: 作用
 * @Author: letquit
 * @CreateDate: 24/10/2021$
 * @Version: 1.0
 */
public class ClaRViewAdapter extends RecyclerView.Adapter<ClaRViewAdapter.ViewHolder> {
    private List<Commodity> list;
    private Context context;
    private String sCommodityTypeName;
    WindowManager windowManager;
    ClaMySQLiteOpenHelper openHelper;
    SQLiteDatabase database;

    public ClaRViewAdapter(List<Commodity> list, Context context, WindowManager windowManager) {
        this.list = list;
        this.context = context;
        this.windowManager = windowManager;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_rv_cla, parent, false);
        return new ViewHolder(view);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ViewHolder vh = (ViewHolder)holder;
        Commodity commodity = list.get(position);
        String id = String.valueOf(commodity.getId());
        String commodityName = commodity.getCommodityName();
        String commodityTypeName = String.valueOf(commodity.getCommodityTypeName());
        String money = commodity.getMoney();
        String costPrice = commodity.getCostPrice();
        String pic = commodity.getPic();
        String volume = commodity.getVolume();
        Glide.with(context).load(pic).into(vh.imgRvClaPic);
        vh.tvRvClaCommodityName.setText(commodityName);
        vh.tvRvClaMoney.setText(money);
        vh.tvRvClaMoney.setPaintFlags(vh.tvRvClaMoney.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        vh.tvRvClaCostPrice.setText(costPrice);
        vh.tvRvClaVolume.setText("销量：" + volume);
        vh.imgRvClaMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Log.i("TAG", commodityName + " " + money + " " + costPrice + " " + volume);
//                弹出dialog
                AlertDialog dialog =new AlertDialog.Builder(context).create();
                dialog.show();
                Window window = dialog.getWindow();
//                设置dialog于底部
                window.setGravity(Gravity.BOTTOM);
//                初始化view
                window.setContentView(R.layout.item_cla_dialog);
//                自定义dialog效果
                window.setWindowAnimations(R.style.mystyle);
                TextView tvClaDiaComName = window.findViewById(R.id.tvClaDiaComName);
                TextView tvClaDiaCla = window.findViewById(R.id.tvClaDiaCla);
                TextView tvClaDiaCostPrice = window.findViewById(R.id.tvClaDiaCostPrice);
                TextView tvClaDiaMoney = window.findViewById(R.id.tvClaDiaMoney);
                TextView tvClaDiaDel = window.findViewById(R.id.tvClaDiaDel);
                TextView tvClaDiaNum = window.findViewById(R.id.tvClaDiaNum);
                TextView tvClaDiaAdd = window.findViewById(R.id.tvClaDiaAdd);
                ImageView imgClaDiaPic = window.findViewById(R.id.imgClaDiaPic);
                Button btnClaDiaOK = window.findViewById(R.id.btnClaDiaOK);
                Button btnClaDiaCancel = window.findViewById(R.id.btnClaDiaCancel);
                tvClaDiaComName.setText(commodityName);
                //        异步取得所有商品分类
                OkHttpUtils.builder()
                        .url("interface/CommodityType/getAll")
                        .addParam("userId", "ODky")
                        .get()
                        .async(new OkHttpUtils.AsyncCallBack() {
                            @Override
                            public void onResponse(String json) {
                                Gson gson = new Gson();
                                CommodityTypeIdInfo typeId = gson.fromJson(json, CommodityTypeIdInfo.class);
                                List<CommodityTypeIdInfo.DataBean> temp = typeId.getData();
                                for (int i = 0; i < temp.size(); i++) {
                                    String commodityTypeId = String.valueOf(temp.get(i).getId());
//                                    根据所选分类id从所有分类中取得分类名字
                                    if (commodityTypeId.equals(commodityTypeName)) {
                                        sCommodityTypeName = temp.get(i).getCommodityTypeName();
                                    }
                                }
//                                刷新UI界面
                                ((Activity) context).runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        tvClaDiaCla.setText(sCommodityTypeName);
                                    }
                                });
                            }

                            @Override
                            public void onFailure(Exception e) {

                            }
                        });
                tvClaDiaCostPrice.setText(costPrice);
                tvClaDiaMoney.setText(money);
                Glide.with(context).load(pic).into(imgClaDiaPic);
//                商品数量至少为1
                tvClaDiaDel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int num = Integer.parseInt(tvClaDiaNum.getText().toString()) - 1;
                        if (num < 1) {
                            Toast.makeText(context, "商品数量不能小于1", Toast.LENGTH_SHORT).show();
                        } else {
                            tvClaDiaNum.setText(String.valueOf(num));
                        }
                    }
                });
//                商品数量最多为99
                tvClaDiaAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int num = Integer.parseInt(tvClaDiaNum.getText().toString()) + 1;
                        if (num > 99) {
                            Toast.makeText(context, "商品数量不能大于99", Toast.LENGTH_SHORT).show();
                        } else {
                            tvClaDiaNum.setText(String.valueOf(num));
                        }
                    }
                });
                btnClaDiaCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });
//                将所选商品数据存储到本地数据库
                btnClaDiaOK.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int num = Integer.parseInt(tvClaDiaNum.getText().toString());
                        float fCostPrice = Float.parseFloat(costPrice);
                        float fMoney = Float.parseFloat(money);
                        String TypeName = tvClaDiaCla.getText().toString();
                        new MyClaDataAdapter().insert(context, new ShopCartInfo(id, commodityName, TypeName, fCostPrice, fMoney, num, pic));
                        dialog.dismiss();
                    }
                });
//                设置LayoutParams为半屏
                WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
                DisplayMetrics dm = new DisplayMetrics();
                windowManager.getDefaultDisplay().getMetrics(dm);
                lp.width = dm.widthPixels;
                lp.height = (int) (dm.heightPixels * 0.5);
                dialog.getWindow().setAttributes(lp);
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ItemRvClaBinding itemBinding;
        ImageView imgRvClaPic, imgRvClaMore;
        TextView tvRvClaCommodityName, tvRvClaCostPrice, tvRvClaMoney, tvRvClaVolume;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            itemBinding = ItemRvClaBinding.bind(itemView);
            imgRvClaPic = itemBinding.imgRvClaPic;
            imgRvClaMore = itemBinding.imgRvClaMore;
            tvRvClaCommodityName = itemBinding.tvRvClaCommodityName;
            tvRvClaCostPrice = itemBinding.tvRvClaCostPrice;
            tvRvClaMoney = itemBinding.tvRvClaMoney;
            tvRvClaVolume = itemBinding.tvRvClaVolume;
        }
    }

}

